<?php
// +----------------------------------------------------------------------
// | User: zq
// +----------------------------------------------------------------------
// | Time: 2021/12/7 11:43
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Services\Goods\GoodsService;
use App\Services\Order\CartService;
use App\Services\Order\OrderService;
use App\Services\Promotion\CouponService;
use App\Services\SystemService;
use App\Services\User\AddressService;
use Illuminate\Http\JsonResponse;

class CartController extends WxController
{
    /**
     * 购物车列表
     * @return JsonResponse
     */
    public function index()
    {
        $list = CartService::getInstance()->getValidCartList($this->userId());
        // 总数量
        $goodsCount = 0;
        // 总金额
        $goodsAmount = 0;
        // 选中的商品数量
        $checkedGoodsCount = 0;
        // 选中的商品金额
        $checkedGoodsAmount = 0;

        foreach ($list as $item) {
            $goodsCount += $item->number;
            $amount = bcmul($item->price, $item->number, 2);
            $goodsAmount = bcadd($goodsAmount, $amount, 2);

            if ($item->checked) {
                $checkedGoodsCount += $item->number;
                $checkedGoodsAmount = bcadd($checkedGoodsAmount, $amount, 2);
            }
        }
        return $this->success([
            'cartList' => $list->toArray(),
            'cartTotal' => [
                'goodsCount' => $goodsCount,
                'goodsAmount' => (double) $goodsAmount,
                'checkedGoodsCount' => $checkedGoodsCount,
                'checkedGoodsAmount' => (double) $checkedGoodsAmount
            ]
        ]);
    }

    /**
     * 立即购买商品
     *
     * 和 add 方法的区别在于:
     * 1. 如果购物车已经存在购物货品,前者的逻辑是数量添加,这里的逻辑是数量覆盖
     * 2. 添加成功以后,前者的逻辑是返回当前购物车商品数量,这里的逻辑是返回对应购物车项的ID
     */
    public function fastadd()
    {
        $goodsId = $this->verifyId('goodsId', 0);
        $productId = $this->verifyId('productId', 0);
        $number = $this->verifyPositiveInteger('number', 0);
        $cart = CartService::getInstance()->fastadd($this->userId(), $goodsId, $productId, $number);
        return $this->success($cart->id);
    }

    /**
     * 加入商品到购物车
     *
     * 如果已经存在购物车货品,则增加数量
     * 否则添加新的购物车货品
     *
     * @return JsonResponse
     */
    public function add()
    {
        $goodsId = $this->verifyId('goodsId', 0);
        $productId = $this->verifyId('productId', 0);
        $number = $this->verifyPositiveInteger('number', 0);
        CartService::getInstance()->add($this->userId(), $goodsId, $productId, $number);
        $count = CartService::getInstance()->countCartProduct($this->userId());
        return $this->success($count);
    }

    /**
     * 获取购物车商品件数
     * @return JsonResponse
     */
    public function goodscount()
    {
        $count = CartService::getInstance()->countCartProduct($this->userId());
        return $this->success($count);
    }

    /**
     * 更新购物车的商品的数量
     * @return JsonResponse
     */
    public function update()
    {
        $id = $this->verifyId('id', 0);
        $goodsId = $this->verifyId('goodsId', 0);
        $productId = $this->verifyId('productId', 0);
        $number = $this->verifyPositiveInteger('number', 0);

        // 购物车是否存在
        $cart = CartService::getInstance()->getCartById($this->userId(), $id);
        if (is_null($cart)) {
            return $this->badArgumentValue();
        }

        // 商品和货品是否存在
        if ($cart->goods_id != $goodsId || $cart->product_id != $productId) {
            return $this->badArgumentValue();
        }

        // 商品是否下架
        $goods = GoodsService::getInstance()->getGoods($goodsId);
        if (is_null($goods) || !$goods->is_on_sale) {
            return $this->fail(CodeResponse::GOODS_UNSHELVE);
        }

        // 商品库存是否足够
        $product = GoodsService::getInstance()->getGoodsProductById($productId);
        if (is_null($product) || $product->number < $number) {
            return $this->fail(CodeResponse::GOODS_NO_STOCK);
        }

        $cart->number = $number;
        $ret = $cart->save();
        return $this->failOrSuccess($ret);
    }

    /**
     * 删除购物车的商品
     */
    public function delete()
    {
        $productIds = $this->verifyArrayNotEmpty('productIds', []);
        CartService::getInstance()->delete($this->userId(), $productIds);
        return $this->index();
    }

    /**
     * 选择或取消选择商品
     */
    public function checked()
    {
        $productIds = $this->verifyArrayNotEmpty('productIds', []);
        $isChecked = $this->verifyBoolean('isChecked');
        CartService::getInstance()->updateChecked($this->userId(), $productIds, $isChecked == 1);
        return $this->index();
    }

    /**
     * 下单前信息确认
     *
     * @param  integer userId     用户id
     * @param  integer cartId     购物车商品id
     *                            如果购物车商品ID是空, 则下单当前用户所有购物车商品.
     *                            如果购物车商品ID非空, 则只下单当前购物车商品.
     * @param  integer addressId  收货地址Id
     *                            如果收货地址ID为空, 则查询当前用户的默认地址.
     *                            如果收货地址ID非空, 则查询自己选择的地址.
     * @param  integer couponId   优惠券id
     *                            如果优惠券id是空,则自动选择合适的优惠券.
     *                            如果优惠券id非空,则查询自己选择的的优惠券.
     * @return JsonResponse
     */
    public function checkout()
    {
        // 购物车id
        $cartId = $this->verifyInteger('cartId');
        // 地址id
        $addressId = $this->verifyInteger('addressId');
        // 优惠券信息及规则表
        $couponId = $this->verifyInteger('couponId');
        // 团购规则表
        $grouponRulesId = $this->verifyInteger('grouponRulesId');

        // 获取地址
        $address = AddressService::getInstance()->getAddressOrDefault($this->userId(), $addressId);
        $addressId = $address->id ?? 0;

        // 获取购物车的商品列表
        $checkedGoodsList = CartService::getInstance()->getCheckedCartlist($this->userId(), $cartId);

        // 计算订单总金额
        $grouponPrice = 0;
        $checkedGoodsPrice = CartService::getInstance()->getCartPriceCutGroupon($checkedGoodsList, $grouponRulesId,
            $grouponPrice);

        // 获取优惠券信息
        $availableCouponLength = 0;
        $couponUser = CouponService::getInstance()->getMostMeetPriceCoupon($this->userId(), $couponId,
            $checkedGoodsPrice, $availableCouponLength);
        if (is_null($couponUser)) {
            $couponId = -1;
            $userCouponId = -1;
            $couponPrice = 0;
        } else {
            $couponId = $couponUser->coupon_id ?? 0;
            $userCouponId = $couponUser->id ?? 0;
            $couponPrice = CouponService::getInstance()->getCoupon($couponId)->discount ?? 0;
        }

        // 运费 (根据订单商品总价计算运费,满88元则免运费,否则8元.)
        $freightPrice = OrderService::getInstance()->getFreight($checkedGoodsPrice);

        // 计算订单的金额
        $orderPrice = bcadd($checkedGoodsPrice, $freightPrice, 2); //加上运费
        $orderPrice = bcsub($orderPrice, $couponPrice, 2); //减去团购金额

        return $this->success([
            "addressId" => $addressId,
            "couponId" => $couponId,
            "userCouponId" => $userCouponId,
            "cartId" => $cartId,
            "grouponRulesId" => $grouponRulesId,
            "grouponPrice" => $grouponPrice,
            "checkedAddress" => $address,
            "availableCouponLength" => $availableCouponLength,
            "goodsTotalPrice" => $checkedGoodsPrice,
            "freightPrice" => $freightPrice,
            "couponPrice" => $couponPrice,
            "orderTotalPrice" => $orderPrice,
            "actualPrice" => $orderPrice,
            "checkedGoodsList" => $checkedGoodsList->toArray(),
        ]);
    }
}